<template>
  <el-dialog
    v-model="visible"
    :title="title"
    width="800px"
    :close-on-click-modal="false"
    @closed="handleClosed"
  >
    <el-form
      ref="formRef"
      :model="formData"
      :rules="formRules"
      label-width="120px"
      label-position="right"
    >
      <el-tabs v-model="activeTab">
        <!-- 基本信息 -->
        <el-tab-pane label="基本信息" name="basic">
          <el-row :gutter="20">
            <el-col :span="12">
              <el-form-item label="数据源名称" prop="name">
                <el-input v-model="formData.name" placeholder="请输入数据源名称" />
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="数据源类型">
                <el-input :value="'HTTP接口'" disabled />
              </el-form-item>
            </el-col>
          </el-row>
          <el-form-item label="描述" prop="description">
            <el-input
              v-model="formData.description"
              type="textarea"
              :rows="3"
              placeholder="请输入数据源描述"
            />
          </el-form-item>
          <el-form-item label="状态" prop="status">
            <el-radio-group v-model="formData.status">
              <el-radio :label="1">启用</el-radio>
              <el-radio :label="0">禁用</el-radio>
            </el-radio-group>
          </el-form-item>
        </el-tab-pane>

        <!-- 连接配置 -->
        <el-tab-pane label="连接配置" name="connection">
          <el-form-item label="API地址" prop="connectionConfig.url">
            <el-input v-model="formData.connectionConfig.url" placeholder="请输入API地址">
              <template #prepend>http://</template>
            </el-input>
          </el-form-item>
          <el-form-item label="请求方法" prop="connectionConfig.method">
            <el-select
              v-model="formData.connectionConfig.method"
              placeholder="请选择请求方法"
              style="width: 100%"
            >
              <el-option label="GET" value="GET" />
              <el-option label="POST" value="POST" />
              <el-option label="PUT" value="PUT" />
              <el-option label="DELETE" value="DELETE" />
              <el-option label="PATCH" value="PATCH" />
            </el-select>
          </el-form-item>
          
          <el-form-item label="请求头" prop="connectionConfig.headers">
            <el-button
              type="primary"
              size="small"
              @click="addHeader"
              style="margin-bottom: 10px"
            >
              添加请求头
            </el-button>
            <el-table
              :data="formData.connectionConfig.headers"
              border
              style="width: 100%"
              empty-text="暂无请求头配置"
            >
              <el-table-column prop="key" label="键名" width="200">
                <template #default="{ row, $index }">
                  <el-input
                    v-model="row.key"
                    placeholder="请输入键名"
                    @change="validateHeaders"
                  />
                </template>
              </el-table-column>
              <el-table-column prop="value" label="键值">
                <template #default="{ row, $index }">
                  <el-input
                    v-model="row.value"
                    placeholder="请输入键值"
                    @change="validateHeaders"
                  />
                </template>
              </el-table-column>
              <el-table-column label="操作" width="80">
                <template #default="{ $index }">
                  <el-button
                    type="danger"
                    size="small"
                    @click="removeHeader($index)"
                  >
                    删除
                  </el-button>
                </template>
              </el-table-column>
            </el-table>
          </el-form-item>

          <el-form-item label="请求参数" prop="connectionConfig.params">
            <el-button
              type="primary"
              size="small"
              @click="addParam"
              style="margin-bottom: 10px"
            >
              添加请求参数
            </el-button>
            <el-table
              :data="formData.connectionConfig.params"
              border
              style="width: 100%"
              empty-text="暂无请求参数配置"
            >
              <el-table-column prop="key" label="参数名" width="200">
                <template #default="{ row, $index }">
                  <el-input
                    v-model="row.key"
                    placeholder="请输入参数名"
                  />
                </template>
              </el-table-column>
              <el-table-column prop="value" label="参数值">
                <template #default="{ row, $index }">
                  <el-input
                    v-model="row.value"
                    placeholder="请输入参数值"
                  />
                </template>
              </el-table-column>
              <el-table-column label="操作" width="80">
                <template #default="{ $index }">
                  <el-button
                    type="danger"
                    size="small"
                    @click="removeParam($index)"
                  >
                    删除
                  </el-button>
                </template>
              </el-table-column>
            </el-table>
          </el-form-item>

          <el-form-item label="请求体" prop="connectionConfig.body" v-if="showRequestBody">
            <el-input
              v-model="formData.connectionConfig.body"
              type="textarea"
              :rows="5"
              placeholder="请输入请求体(JSON格式)"
            />
          </el-form-item>

          <el-form-item label="超时时间(ms)" prop="connectionConfig.timeout">
            <el-input-number
              v-model="formData.connectionConfig.timeout"
              :min="100"
              :max="30000"
              controls-position="right"
              style="width: 100%"
            />
          </el-form-item>
        </el-tab-pane>

        <!-- 数据格式配置 -->
        <el-tab-pane label="数据格式" name="dataFormat">
          <el-form-item label="响应格式" prop="dataFormatConfig.format">
            <el-select
              v-model="formData.dataFormatConfig.format"
              placeholder="请选择响应格式"
              style="width: 100%"
            >
              <el-option label="JSON" value="JSON" />
              <el-option label="XML" value="XML" />
              <el-option label="Text" value="TEXT" />
            </el-select>
          </el-form-item>

          <el-form-item label="数据根路径" prop="dataFormatConfig.rootPath">
            <el-input
              v-model="formData.dataFormatConfig.rootPath"
              placeholder="例如: data.list (留空表示使用整个响应体)"
            />
          </el-form-item>

          <el-form-item label="编码格式" prop="dataFormatConfig.encoding">
            <el-select
              v-model="formData.dataFormatConfig.encoding"
              placeholder="请选择编码格式"
              style="width: 100%"
            >
              <el-option label="UTF-8" value="UTF-8" />
              <el-option label="GBK" value="GBK" />
              <el-option label="ISO-8859-1" value="ISO-8859-1" />
            </el-select>
          </el-form-item>
        </el-tab-pane>

        <!-- 高级配置 -->
        <el-tab-pane label="高级配置" name="advanced">
          <el-form-item label="缓存配置" prop="cacheConfig.enabled">
            <el-switch
              v-model="formData.cacheConfig.enabled"
              active-text="启用缓存"
              inactive-text="禁用缓存"
            />
          </el-form-item>
          <el-form-item
            v-if="formData.cacheConfig.enabled"
            label="缓存时间(秒)"
            prop="cacheConfig.ttl"
          >
            <el-input-number
              v-model="formData.cacheConfig.ttl"
              :min="60"
              :max="86400"
              controls-position="right"
              style="width: 100%"
            />
          </el-form-item>

          <el-form-item label="重试策略" prop="retryConfig.enabled">
            <el-switch
              v-model="formData.retryConfig.enabled"
              active-text="启用重试"
              inactive-text="禁用重试"
            />
          </el-form-item>
          <template v-if="formData.retryConfig.enabled">
            <el-form-item label="重试次数" prop="retryConfig.maxAttempts">
              <el-input-number
                v-model="formData.retryConfig.maxAttempts"
                :min="1"
                :max="5"
                controls-position="right"
                style="width: 100%"
              />
            </el-form-item>
            <el-form-item label="重试间隔(ms)" prop="retryConfig.interval">
              <el-input-number
                v-model="formData.retryConfig.interval"
                :min="1000"
                :max="10000"
                controls-position="right"
                style="width: 100%"
              />
            </el-form-item>
          </template>
        </el-tab-pane>
      </el-tabs>
    </el-form>

    <template #footer>
      <span class="dialog-footer">
        <el-button @click="visible = false">取消</el-button>
        <el-button type="primary" @click="submitForm">确认</el-button>
      </span>
    </template>
  </el-dialog>
</template>

<script>
import { ref, computed, watch } from 'vue'
import { ElMessage } from 'element-plus'

export default {
  name: 'EditHttpDialog',
  props: {
    modelValue: {
      type: Boolean,
      default: false
    },
    editData: {
      type: Object,
      default: null
    }
  },
  emits: ['update:modelValue', 'submit'],
  setup(props, { emit }) {
    const visible = computed({
      get: () => props.modelValue,
      set: (val) => emit('update:modelValue', val)
    })

    const title = computed(() => 
      props.editData ? '编辑HTTP数据源' : '新增HTTP数据源'
    )

    const activeTab = ref('basic')
    const formRef = ref(null)

    // 默认表单数据
    const defaultFormData = {
      id: '',
      name: '',
      description: '',
      status: 1,
      connectionConfig: {
        url: '',
        method: 'GET',
        headers: [],
        params: [],
        body: '',
        timeout: 5000
      },
      dataFormatConfig: {
        format: 'JSON',
        rootPath: '',
        encoding: 'UTF-8'
      },
      cacheConfig: {
        enabled: true,
        ttl: 3600
      },
      retryConfig: {
        enabled: false,
        maxAttempts: 3,
        interval: 3000
      }
    }

    const formData = ref(JSON.parse(JSON.stringify(defaultFormData)))

    // 是否需要显示请求体字段
    const showRequestBody = computed(() => {
      return ['POST', 'PUT', 'PATCH'].includes(formData.value.connectionConfig.method)
    })

    // 表单验证规则
    const formRules = {
      name: [
        { required: true, message: '请输入数据源名称', trigger: 'blur' },
        { max: 100, message: '长度不能超过100个字符', trigger: 'blur' }
      ],
      'connectionConfig.url': [
        { required: true, message: '请输入API地址', trigger: 'blur' },
        { 
          validator: (rule, value, callback) => {
            if (!value) return callback()
            try {
              new URL(value.startsWith('http') ? value : `http://${value}`)
              callback()
            } catch (e) {
              callback(new Error('请输入有效的URL地址'))
            }
          },
          trigger: 'blur'
        }
      ],
      'connectionConfig.method': [
        { required: true, message: '请选择请求方法', trigger: 'change' }
      ],
      'connectionConfig.headers': [
        {
          validator: (rule, value, callback) => {
            if (!value || value.length === 0) return callback()
            const hasEmpty = value.some(item => !item.key || !item.value)
            if (hasEmpty) {
              callback(new Error('请求头键名和键值不能为空'))
            } else {
              callback()
            }
          },
          trigger: 'change'
        }
      ],
      'dataFormatConfig.format': [
        { required: true, message: '请选择响应格式', trigger: 'change' }
      ],
      'cacheConfig.ttl': [
        { required: true, message: '请输入缓存时间', trigger: 'blur' }
      ]
    }

    // 添加请求头
    const addHeader = () => {
      formData.value.connectionConfig.headers.push({
        key: '',
        value: ''
      })
    }

    // 删除请求头
    const removeHeader = (index) => {
      formData.value.connectionConfig.headers.splice(index, 1)
      validateHeaders()
    }

    // 验证请求头
    const validateHeaders = () => {
      formRef.value.validateField('connectionConfig.headers')
    }

    // 添加请求参数
    const addParam = () => {
      formData.value.connectionConfig.params.push({
        key: '',
        value: ''
      })
    }

    // 删除请求参数
    const removeParam = (index) => {
      formData.value.connectionConfig.params.splice(index, 1)
    }

    // 对话框关闭
    const handleClosed = () => {
      formRef.value?.resetFields()
      formData.value = JSON.parse(JSON.stringify(defaultFormData))
    }

    // 提交表单
    const submitForm = async () => {
      try {
        await formRef.value.validate()
        
        // 处理请求头和参数，过滤空值
        const finalData = JSON.parse(JSON.stringify(formData.value))
        finalData.connectionConfig.headers = finalData.connectionConfig.headers
          .filter(item => item.key && item.value)
        finalData.connectionConfig.params = finalData.connectionConfig.params
          .filter(item => item.key && item.value)
        
        // 如果不需要请求体，清空body字段
        if (!showRequestBody.value) {
          finalData.connectionConfig.body = ''
        }
        console.log(finalData);
        emit('submit', finalData)
        visible.value = false
      } catch (error) {
        console.error('表单验证失败:', error)
        ElMessage.error('请检查表单填写是否正确')
      }
    }

    // 监听编辑数据变化
    watch(() => props.editData, (newVal) => {
      if (newVal) {
        formData.value = JSON.parse(JSON.stringify({
          ...defaultFormData,
          ...newVal,
          connectionConfig: {
            ...defaultFormData.connectionConfig,
            ...(newVal.connectionConfig || {})
          },
          dataFormatConfig: {
            ...defaultFormData.dataFormatConfig,
            ...(newVal.dataFormatConfig || {})
          },
          cacheConfig: {
            ...defaultFormData.cacheConfig,
            ...(newVal.cacheConfig || {})
          },
          retryConfig: {
            ...defaultFormData.retryConfig,
            ...(newVal.retryConfig || {})
          }
        }))
        
        // 确保headers和params是数组
        if (!Array.isArray(formData.value.connectionConfig.headers)) {
          formData.value.connectionConfig.headers = []
        }
        if (!Array.isArray(formData.value.connectionConfig.params)) {
          formData.value.connectionConfig.params = []
        }
      }
    }, { immediate: true })

    return {
      visible,
      title,
      activeTab,
      formRef,
      formData,
      formRules,
      showRequestBody,
      addHeader,
      removeHeader,
      validateHeaders,
      addParam,
      removeParam,
      handleClosed,
      submitForm
    }
  }
}
</script>

<style scoped>
.el-input-with-prepend :deep(.el-input-group__prepend) {
  width: 80px;
}
</style>